package com.chezai.client.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.widget.Button;
import android.widget.TextView;

import com.chezai.client.R;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 倒计时弹窗
 * Created by likunyang on 2017/9/21.
 */

public class CountDownDialog extends BaseDialog implements DialogInterface.OnShowListener, DialogInterface.OnDismissListener {

    @BindView(R.id.tv_seconds)
    TextView tvSeconds;
    @BindView(R.id.btn_cancel)
    Button btnCancel;
    private int mCountDownTime;
    private CountDownTimer countDownTimer;
    private onCountDownDialogEventListener listener;

    public CountDownDialog(@NonNull Context context) {
        super(context);
    }

    /**
     * @param countDownTime 倒计时时长
     */
    public CountDownDialog(@NonNull Context context, int countDownTime) {
        this(context);
        this.mCountDownTime = countDownTime;
    }

    @Override
    protected int getDialogLayoutResId() {
        return R.layout.dialog_take_photo;
    }

    @Override
    protected void initView(Context context) {

    }

    @Override
    protected float getwScale() {
        return 0;
    }

    @Override
    protected float gethScale() {
        return 0;
    }

    @Override
    protected int getGravity() {
        return 0;
    }

    @Override
    protected void setListener() {
        setOnShowListener(this);
        setOnDismissListener(this);
    }

    @Override
    public void onShow(DialogInterface dialog) {
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        startCountDownTime();
    }

    private void startCountDownTime() {
        countDownTimer = new CountDownTimer(mCountDownTime * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tvSeconds.setText(millisUntilFinished / 1000 + " ");
            }
            @Override
            public void onFinish() {
                if (listener != null) {
                    listener.onFinish(CountDownDialog.this);
                }
            }
        };
        countDownTimer.start();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }


    @OnClick(R.id.btn_cancel)
    public void onViewClicked() {
        if (listener != null) {
            listener.onCancel(this);
        }
    }

    public void setOnCountDownDialogEventListener(onCountDownDialogEventListener listener) {
        this.listener = listener;
    }

    public interface onCountDownDialogEventListener {
        void onFinish(Dialog dialog);

        void onCancel(Dialog dialog);
    }
}
